﻿using ProjectScheduling.daos;
using ProjectScheduling.models;
using System.Data;

namespace ProjectScheduling
{
    public partial class WarnForm : Form
    {
        public static readonly WarnForm b = new();
        /// <summary>
        /// 默认最后提醒时间为昨天。（保证 今天 刚开机 就更新提醒日期）
        /// </summary>
        private DateTime WarningTime = DateTime.Today.AddDays(-1);
        private readonly List<Enum_ProjectState> OkStates = [Enum_ProjectState.已排期, Enum_ProjectState.实施中];
        public WarnForm()
        {
            InitializeComponent();
            view_all.AutoGenerateColumns = false;
            SetForm();
            //Search();
            CheckState();
        }
        private void CheckState()
        {
            if (WarningTime < DateTime.Now.AddHours(-4))
            {
                var startTime = DateTime.Now.AddHours(-4);
                var checkIds = StateRecordDao.Base.FindAll(it => it.CreateTime > startTime).Select(it => it.ProjectId).ToList();
                if (ProjectDao.Base.Exists(it => it.FromDate < DateTime.Now && OkStates.Contains(it.State) && !checkIds.Contains(it.Id)))
                {
                    WarningTime = DateTime.Now;
                    Search();
                    ShowDialog();
                }
                else
                {
                    WarningTime = DateTime.Now;
                }
            }
        }
        private void SetForm()
        {
            TransparencyKey = Color.Blue;

            Width = Screen.AllScreens[0].Bounds.Width;
            Height = Screen.AllScreens[0].Bounds.Height;
            p_main.SetBounds(Width / 10, Height / 10, Width * 8 / 10, Height * 8 / 10);
        }
        private void Search()
        {
            var startTime = DateTime.Now.AddHours(-4);
            var checkIds = StateRecordDao.Base.FindAll(it => it.CreateTime > startTime).Select(it => it.ProjectId).ToList();
            var datas = ProjectDao.Base.FindAll(it => !checkIds.Contains(it.Id) && it.FromDate < DateTime.Now && OkStates.Contains(it.State));
            if (datas.Count == 0)
            {
                if (Visible)
                    Close();
                return;
            }
            var table = new DataTable();
            new List<string> { "Id", "Name", "FromData", "ToData", "Reason", "Staffs", "State", "Rate" }.ForEach(it => table.Columns.Add(it));
            datas.ForEach(item =>
            {
                //var startOut = item.FromDate < DateTime.Now && item.State == models.Enum_ProjectState.已排期;
                var stateInt = item.FromDate < DateTime.Now ? (item.ToDate < DateTime.Now ? 2 : 1) : 0;
                var row = table.NewRow();
                row["Id"] = item.Id;
                row["Name"] = item.Name;
                row["FromData"] = item.FromDate;
                row["ToData"] = item.ToDate;
                row["Reason"] = new string[] { "待施工", "待更新施工状态", "待完工" }[stateInt]; // startOut ? "开始时间已过" : "结束时间已过";
                row["Staffs"] = string.Join("、", item.StaffsList?.Select(s => s.UserName) ?? []);
                row["State"] = stateInt;
                row["Rate"] = item.Rate;
                table.Rows.Add(row);
            });
            view_all.DataSource = table;

        }
        /// <summary>
        /// 单元格单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void View_all_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            if (e.ColumnIndex != 7) return;
            if (view_all.DataSource is not DataTable table) return;
            var row = table.Rows[e.RowIndex];
            int toInt(string name) => Convert.ToInt32(row[name]);
            WarnOperatorForm.b.action = () =>
            {
                table.Rows.RemoveAt(e.RowIndex);
                if (table.Rows.Count == 0)
                {
                    if (Visible)
                        Close();
                }
                //view_all.Rows.RemoveAt(e.RowIndex);
            };
            WarnOperatorForm.b.Init(toInt("Id"), toInt("State"), toInt("Rate"));
            WarnOperatorForm.b.ShowDialog();
        }

        private void View_all_SelectionChanged(object sender, EventArgs e)
        {
            view_all.ClearSelection();
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            CheckState();
        }

        private void View_all_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (e.RowIndex < 0) return;
            if (view_all.DataSource is not DataTable dt) return;

            var style = view_all.Rows[e.RowIndex].DefaultCellStyle ?? new DataGridViewCellStyle();
            switch (Convert.ToInt32(dt.Rows[e.RowIndex]["State"]))
            {
                case 0:
                    style.BackColor = Color.Gray;
                    break;
                case 1:
                    style.BackColor = Color.Green;
                    style.ForeColor = Color.Yellow;
                    break;
                case 2:
                    style.BackColor = Color.DarkRed;
                    style.ForeColor = Color.Yellow;
                    break;
            }
        }

        private void WarnForm_KeyPress(object sender, KeyPressEventArgs e)
        {
            Console.WriteLine(e.KeyChar);
        }

        private void view_all_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 27)
            {
                Close();
            }
        }
    }
}
